import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message, Row, Col } from 'antd';
import { UserOutlined, LockOutlined, SafetyOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { authAPI } from '../../services/api';
import { setAdminToken, setAdminUserInfo } from '../../utils/auth';
import './Login.css';

const AdminLogin = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [captcha, setCaptcha] = useState('');
  const navigate = useNavigate();

  // 生成随机验证码
  const generateCaptcha = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 4; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setCaptcha(result);
  };

  useEffect(() => {
    generateCaptcha();
  }, []);

  const onFinish = async (values) => {
    if (values.captcha.toLowerCase() !== captcha.toLowerCase()) {
      message.error('验证码错误');
      generateCaptcha();
      return;
    }

    setLoading(true);
    try {
      const response = await authAPI.adminLogin(values.username, values.password);
      if (response.success) {
        setAdminToken(response.data.token);
        setAdminUserInfo(response.data.user);
        message.success('登录成功');
        navigate('/admin');
      } else {
        message.error(response.message);
        generateCaptcha();
      }
    } catch (error) {
      message.error('登录失败，请稍后重试');
      console.log("dhasj");
      generateCaptcha();
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="admin-login-container" style={{ background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)' }}>
      <Card className="login-card" title="管理员登录" bordered={false}>
        <Form
          form={form}
          name="adminLogin"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名至少3位' }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              allowClear
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 4, message: '密码至少4位' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              allowClear
            />
          </Form.Item>

          <Form.Item
            name="captcha"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <Row gutter={8}>
              <Col span={14}>
                <Input
                  prefix={<SafetyOutlined />}
                  placeholder="验证码"
                  allowClear
                />
              </Col>
              <Col span={10}>
                <div className="captcha-code" onClick={generateCaptcha}>
                  {captcha}
                </div>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <div className="login-tips">
          <p>测试账号：</p>
          <p>超级管理员: superadmin / admin</p>
          <p>商品管理员: productadmin / admin</p>
          <p>订单管理员: orderadmin / admin</p>
        </div>
      </Card>
    </div>
  );
};

export default AdminLogin; 